package com.tenghui.assisting.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.tenghui.common.utils.DateUtils;
import com.tenghui.common.utils.SecurityUtils;
import com.tenghui.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tenghui.assisting.mapper.FarmersMapper;
import com.tenghui.assisting.domain.Farmers;
import com.tenghui.assisting.service.IFarmersService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.util.CollectionUtils;
import com.tenghui.common.enums.AuthStatus;

import static com.tenghui.common.core.domain.AjaxResult.error;
import static com.tenghui.common.utils.SecurityUtils.getUserId;

/**
 * 农户Service业务层处理
 *
 * @author tenghui
 * @date 2025-10-04
 */
@Service
public class FarmersServiceImpl implements IFarmersService {
    @Autowired
    private FarmersMapper farmersMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 查询农户
     *
     * @param farmersId 农户主键
     * @return 农户
     */
    @Override
    public Farmers selectFarmersByFarmersId(String farmersId) {
        return farmersMapper.selectFarmersByFarmersId(farmersId);
    }

    /**
     * 查询农户列表
     *
     * @param farmers 农户
     * @return 农户
     */
    @Override
    public List<Farmers> selectFarmersList(Farmers farmers) {return farmersMapper.selectFarmersList(farmers);
    }

    /**
     * 新增农户
     *
     * @param farmers 农户
     * @return 结果
     */
    @Override
    public int insertFarmers(Farmers farmers) {
        farmers.setCreateTime(DateUtils.getNowDate());
        // 设置FarmersId和UserId的默认值
        farmers.setFarmersId(IdUtils.fastSimpleUUID());
        farmers.setUserId(getUserId());
        // 设置认证状态为"待认证"（字典键值"1"）
        if (farmers.getAuthStatus() == null) {
            farmers.setAuthStatus(AuthStatus.WAITING_AUTH.getCode());
        }
        return farmersMapper.insertFarmers(farmers);
    }

    /**
     * 批量新增农户
     *
     * @param farmerss 农户List
     * @return 结果
     */
    @Override
    public int batchInsertFarmers(List<Farmers> farmerss) {
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        int count = 0;
        if (!CollectionUtils.isEmpty(farmerss)) {
            try {
                for (int i = 0; i < farmerss.size(); i++) {
                    int row = farmersMapper.insertFarmers(farmerss.get(i));
                    // 防止内存溢出，每100次提交一次,并清除缓存
                    boolean bool = (i > 0 && i % 100 == 0) || i == farmerss.size() - 1;
                    if (bool) {
                        sqlSession.commit();
                        sqlSession.clearCache();
                    }
                    count = i + 1;
                }
            } catch (Exception e) {
                e.printStackTrace();
                // 没有提交的数据可以回滚
                sqlSession.rollback();
            } finally {
                sqlSession.close();
                return count;
            }
        }
        return count;
    }

    /**
     * 修改农户
     *
     * @param farmers 农户
     * @return 结果
     */
    @Override
    public int updateFarmers(Farmers farmers) {
        return farmersMapper.updateFarmers(farmers);
    }

    /**
     * 批量删除农户
     *
     * @param farmersIds 需要删除的农户主键
     * @return 结果
     */
    @Override
    public int deleteFarmersByFarmersIds(String[] farmersIds) {
        return farmersMapper.deleteFarmersByFarmersIds(farmersIds);
    }

    /**
     * 删除农户信息
     *
     * @param farmersId 农户主键
     * @return 结果
     */
    @Override
    public int deleteFarmersByFarmersId(String farmersId) {
        return farmersMapper.deleteFarmersByFarmersId(farmersId);
    }

    /*
     * 查询用户的农户认证信息
     * 返回 审核状态 + 拒绝理由
     */
    @Override
    public Map<String,Object> getAuthStatusInfo() {
        Map<String, Object> result = new HashMap<>();
        // 当前用户的id
        Long userId = getUserId();
        // 查询农户ID

        // 查询当前用户有没有提交过
        Boolean isSubmit = farmersMapper.selectIsSubmit(userId);

        if (isSubmit) {
            // 查询提交状态
            String authStatus = farmersMapper.selectIsAuthStatus(userId);
            // 只有认证失败了 返回拒绝理由
            if("3".equals(authStatus)){
                // 查询当前用户的农户ID
                String farmersId = farmersMapper.selectFarmersIdByUserId(userId);
                result.put("rejectReason",farmersMapper.selectRejectReasonByFarmersId(farmersId));
            }
            result.put("authStatus", authStatus);
        } else {
            // 没有提交过，返回未提交的枚举
            result.put("authStatus", AuthStatus.NOT_SUBMITTED.getCode());
        }
        return result;
    }

    /*
     * 重新认证按钮 更新拒绝状态
     */
    @Override
    public int updateAuthRejectInfo(Farmers farmers) {
        // 当前用户的id
        Long userId = getUserId();
        // 当前农户id
        String farmersId = farmersMapper.selectFarmersIdByUserId(userId);
        if (farmersId == null) error("农户信息不存在");
        // 删除原有记录
        int deleteResult = farmersMapper.deleteFarmersByFarmersId(farmersId);
        if(deleteResult <= 0) error("删除原有认证记录失败");
        return deleteResult;
    }
}
